using System;
using UnityEngine;

namespace Anima2D
{
	[Serializable]
	public class IkSolver2DLimb : IkSolver2D
	{
		public bool flip;
		private Transform tf;

		private Quaternion _cachedRot1 = Quaternion.identity;
		private Quaternion _cachedRot2 = Quaternion.identity;
		private float _cachedZ1, _cachedZ2;
		private const float AngleThreshold = 0.5f;
		private static readonly bool isWebgl = Application.platform == RuntimePlatform.WebGLPlayer;

		Transform _tf
		{
			get
			{
				if (tf == null) tf = base.rootBone.transform;
				return tf;
			}

		}

		protected override void DoSolverUpdate()
		{
			if (isWebgl && Time.frameCount % 2 != 0) return;

			if ((bool)base.rootBone && base.solverPoses.Count == 2)
			{
				SolverPose solverPose = base.solverPoses[0];
				SolverPose solverPose2 = base.solverPoses[1];
				Vector3 vector = targetPosition - _tf.position;
				vector.z = 0f;
				float magnitude = vector.magnitude;
				float num = 0f;
				float num2 = 0f;
				float sqrMagnitude = vector.sqrMagnitude;
				float num3 = solverPose.bone.length * solverPose.bone.length;
				float num4 = solverPose2.bone.length * solverPose2.bone.length;
				float num5 = (sqrMagnitude + num3 - num4) / (2f * solverPose.bone.length * magnitude);
				float num6 = (sqrMagnitude - num3 - num4) / (2f * solverPose.bone.length * solverPose2.bone.length);

				if (num5 >= -1f && num5 <= 1f && num6 >= -1f && num6 <= 1f)
				{
					num = Mathf.Acos(num5) * 57.29578f;
					num2 = Mathf.Acos(num6) * 57.29578f;
				}
				float num7 = ((!flip) ? 1f : (-1f));
				Vector3 direction = MyProjectOnPlane(targetPosition - _tf.position, _tf.forward);
				if ((bool)_tf.parent)
				{
					direction = _tf.parent.InverseTransformDirection(direction);
				}
				float num8 = Mathf.Atan2(direction.y, direction.x) * 57.29578f;
				//solverPose.solverRotation = Quaternion.Euler(0f, 0f, num8 - num7 * num);
				//solverPose2.solverRotation = Quaternion.Euler(0f, 0f, num7 * num2);

				//solverPose.solverRotation = Quaternion.AngleAxis(num8 - num7 * num, Vector3.forward);
				//solverPose2.solverRotation = Quaternion.AngleAxis(num7 * num2, Vector3.forward);

				float targetZ1 = num8 - num7 * num;
				float targetZ2 = num7 * num2;

				// 增量更新
				if (Mathf.Abs(targetZ1 - _cachedZ1) > AngleThreshold)
				{
					_cachedRot1 = Quaternion.AngleAxis(targetZ1, Vector3.forward);
					_cachedZ1 = targetZ1;
					solverPose.solverRotation = _cachedRot1;
				}
				if (Mathf.Abs(targetZ2 - _cachedZ2) > AngleThreshold)
				{
					_cachedRot2 = Quaternion.AngleAxis(targetZ2, Vector3.forward);
					_cachedZ2 = targetZ2;
					solverPose2.solverRotation = _cachedRot2;
				}
			}
		}

		Vector3 MyProjectOnPlane(Vector3 v, Vector3 normal)
		{
			return v - Vector3.Dot(v, normal) * normal;
		}
	}
}
